﻿using System.IO;
using System.Collections.Generic;
using System.Text;

namespace AllFilesSearcher
{
    class AllFilesSearcher
    {
        const string RequiredFilePattern = "*.txt";

        static string GetStringLineFromFile(string str, string fileName)
        {
            StreamReader reader = new StreamReader(fileName);
            using (reader)
            {
                string line = reader.ReadLine();
                while (line != null)
                {
                    string lineLower = line.ToLower();
                    string strToLower = str.ToLower();
                    if (lineLower.Contains(strToLower))
                    {
                        return line;
                    }
                    line = reader.ReadLine();
                }
            }
            return null;
        }

        static void AddFilesToList(DirectoryInfo directory, ref List<FileInfo> files, string searchPattern = RequiredFilePattern)
        {
            FileInfo[] filesInfo = directory.GetFiles(searchPattern);
            foreach (FileInfo fileInfo in filesInfo)
            {
                files.Add(fileInfo);
            }
            DirectoryInfo[] subdirectories = directory.GetDirectories();
            foreach (DirectoryInfo subdirectory in subdirectories)
            {
                AddFilesToList(subdirectory, ref files);
            }
        }

        static void WriteToFile(string fileName, string text)
        {
            StreamWriter writer = new StreamWriter(fileName);
            using (writer)
            {
                writer.Write(text);
            }
        }

        static void Main()
        {
            string directory = @"..\..\SearchHere\";
            string textToSearch = "myst";
            string resultsFile = @"..\..\result.txt";
            DirectoryInfo searchDirectory = new DirectoryInfo(directory);
            List<FileInfo> allTextFiles = new List<FileInfo>();
            AddFilesToList(searchDirectory, ref allTextFiles);
            StringBuilder requiredInfo = new StringBuilder();
            foreach (FileInfo textFile in allTextFiles)
            {
                string line = GetStringLineFromFile(textToSearch, textFile.FullName);
                if (line != null)
                {
                    requiredInfo.AppendLine(textFile.FullName + ":");
                    requiredInfo.AppendLine("\t" + line);
                }
            }
            WriteToFile(resultsFile, requiredInfo.ToString());
        }
    }
}
